package com.example.exam.exception;


import com.example.exam.util.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author : DGUT.YE
 * @date : 2020/09/25
 **/

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    /**
     * 处理servlet异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServletException.class)
    @ResponseBody
    public RespBean servletExceptionHandler(HttpServletRequest req, ServletException e){
        log.error("web服务器异常 {}",e.getMessage());
        return RespBean.error(e.getMessage());
    }

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public  RespBean bizExceptionHandler(HttpServletRequest req, ServiceException e){
        log.error("业务异常=>{}",e.getMessage());
        return RespBean.error(e.getMessage());
    }


    /**
     * 处理验证异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public  RespBean validExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e){
        log.error("验证异常=>{}",e.getMessage());
        return RespBean.error(e.getMessage());
    }


    /**
     * 捕捉其他所有异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespBean globalException(HttpServletRequest request, Throwable ex) {
        String message = ex.getMessage();
        log.error("系统异常=>{}",ex.getMessage());
        ex.printStackTrace();
        return new RespBean(getStatus(request).value(), "系统异常"+message, null);
    }

    /**
     * 获取状态码
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}

